const arr = [1,0,1,4,1,4,1,2,3]

var totalFruit = function(fruits) {
  if (fruits.length === 1) return 1
  let res = 0
  let ans = []
  let i = 0, k = 0, j = 0
  const len = fruits.length
  while (j < len) {
      if (ans.indexOf(fruits[j]) === -1 && ans.length < 2) {
          k = j
          ans.push(fruits[j])
      } else if (ans.indexOf(fruits[j]) !== -1 && ans.length === 2) {
          if (fruits[j] !== fruits[j - 1]) {
              k = j
          }
      } else if (ans.indexOf(fruits[j]) === -1 && ans.length === 2) {
          res = Math.max(res, j - i)
          i = k
          k = j
          ans = ans.filter(item => item === fruits[i])
          ans.push(fruits[j])
      }
      console.log(i, j, k);
      console.log(res, ans);
      j++
  }
  res = Math.max(res, j - i)
  return res
};

console.log(totalFruit(arr))